import React, { useState, useRef, useEffect, Component } from 'react';
import * as THREE from 'three';
import Sensor from './components/Sensor.js';
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls.js';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js';
import { CSS2DObject, CSS2DRenderer } from 'three/examples/jsm/renderers/CSS2DRenderer';
import smoke_jpg from '@/assets/smoke.jpg';
import { PageContainer } from '@ant-design/pro-layout';
import { getSensorsByModel } from './service';
import mqtt from 'mqtt';
import { EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons';
window.THREE = THREE;
import './index.less';
const host = 'ws://broker.emqx.io:8083/mqtt';
const clientId = 'mqttjs_' + Math.random().toString(16).substr(2, 8);
const options = {
  keepalive: 30,
  clientId: clientId,
  protocolId: 'MQTT',
  protocolVersion: 4,
  clean: true,
  reconnectPeriod: 1000,
  connectTimeout: 30 * 1000,
  will: {
    topic: 'WillMsg',
    payload: 'Connection Closed abnormally..!',
    qos: 0,
    retain: false,
  },
  rejectUnauthorized: false,
};
const Detail = () => {
  const [connectionStatus, setConnectionStatus] = useState(false);
  const [messages, setMessages] = useState([]);
  const [sensors, setSensors] = useState([]);
  const scene = new THREE.Scene(); //场景构建
  // const camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 1000);
  const [labelVisible, setLabelVisible] = useState(true);
  const toggleSensorLabels = () => {
    sensors.forEach((sensor) => {
      sensor._label.visible = !labelVisible;
    });
    setLabelVisible(!labelVisible);
  };
  function onDocumentMouseDown(event) {
    event.preventDefault();
    var vector = new THREE.Vector3(); //三维坐标对象
    vector.set(
      (event.clientX / window.innerWidth) * 2 - 1,
      -(event.clientY / window.innerHeight) * 2 + 1,
      0.5,
    );
    vector.unproject(camera);
    var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
    var intersects = raycaster.intersectObjects(scene.children);
    if (intersects.length > 0) {
      var selected = intersects[0]; //取第一个物体
      console.log('x坐标:' + selected.point.x);
      console.log('y坐标:' + selected.point.y);
      console.log('z坐标:' + selected.point.z);
    }
  }
  //mqtt连接
  useEffect(() => {
    const client = mqtt.connect(host, options);
    client.on('connect', () => {
      setConnectionStatus(true);
      client.subscribe('testtopic', { qos: 0 });
      client.publish('testtopic', 'ws connection demo...!', { qos: 0, retain: false });
    });
    client.on('message', (topic, message, packet) => {
      console.log('Received Message: ' + message.toString() + '\nOn topic: ' + topic);
    });

    client.on('error', (err) => {
      console.log('Connection error: ', err);
      client.end();
    });
    client.on('reconnect', () => {
      console.log('Reconnecting...');
    });
    client.on('close', () => {
      console.log(clientId + ' disconnected');
    });
  }, []);

  useEffect(() => {
    async function getSensors() {
      let res = await getSensorsByModel();
      // setSensors(res.data);
      // res.data.forEach((x) => {
      //   let sensor = new Sensor(x.id,x.category_id, x.axis_x, x.axis_y, x.axis_z, x.direction);
      //   scene.add(sensor._mesh);
      // });

      let sensor = new Sensor('123', 1, 6, 4, 4, '朝前');
      let sensor2 = new Sensor('345', 2, -5, 3, 8.5, '朝前');
      let sensor3 = new Sensor('678', 3, -1, 2, 1, '朝前');
      scene.add(sensor._mesh);
      scene.add(sensor2._mesh);
      scene.add(sensor3._mesh);
      setSensors([sensor, sensor2, sensor3]);
    }
    getSensors();
  }, []);

  useEffect(() => {
    //编辑代码处
    var container = document.getElementById('canvas-frame');
    var width = container.clientWidth;
    var height = container.clientHeight;

    // var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 1000); //相机构建
    // var k = width / height; //窗口宽高比
    // var s = 150; //三维场景显示范围控制系数，系数越大，显示的范围越大
    // var camera = new THREE.OrthographicCamera(-s * k, s * k, s, -s, 1, 1000);
    var renderer = new THREE.WebGLRenderer(); //渲染器构建
    renderer.setPixelRatio(window.devicePixelRatio);
    container.appendChild(renderer.domElement);
    renderer.setClearColor(0xeeeeee);
    renderer.setSize(width, height);

    // var camera_helper = new THREE.CameraHelper(camera);
    // scene.add(camera_helper);
    // //构建一个辅助的坐标轴
    // var axes = new THREE.AxesHelper(100);
    // scene.add(axes);
    let inner = document.getElementById('inner-label');
    let div = document.getElementById('control-label');
    var labelRenderer = new CSS2DRenderer();
    labelRenderer.setSize(width, height);
    labelRenderer.domElement.style.position = 'absolute';
    labelRenderer.domElement.style.top = 0;
    container.appendChild(labelRenderer.domElement);
    labelRenderer.domElement.appendChild(inner);
    // div.appendChild(inner)
    //创建控件并绑定在相机上
    var trackballControls = new TrackballControls(camera, labelRenderer.domElement);
    trackballControls.rotateSpeed = 3.0;
    trackballControls.zoomSpeed = 3.0;
    trackballControls.panSpeed = 1.0;
    trackballControls.noZoom = false;
    trackballControls.noPan = false;
    trackballControls.staticMoving = true;
    trackballControls.dynamicDampingFactor = 0.3;

    var planeGeometry = new THREE.PlaneGeometry(40, 20);
    var planeMaterial = new THREE.MeshBasicMaterial({ color: 0xcccccc });
    // var planeMaterial = new THREE.MeshLambertMaterial({color:0xffffff});//转换对光源有渲染的材质
    var plane = new THREE.Mesh(planeGeometry, planeMaterial);
    plane.rotation.x = -0.5 * Math.PI;
    plane.position.x = 15;
    plane.position.y = 0;
    plane.position.x = 0;
    // scene.add(plane);
    plane.receiveShadow = true;
    //添加材质灯光阴影
    var ambient = new THREE.AmbientLight(0xffffff);
    scene.add(ambient);

    var directionalLight = new THREE.DirectionalLight(0xffffff);
    scene.add(directionalLight);

    var texture_loader = new THREE.TextureLoader();
    var texture = texture_loader.load(smoke_jpg);
    var geometry1 = new THREE.CylinderGeometry(1, 1, 0.2, 64);
    var material1 = new THREE.MeshLambertMaterial({
      color: 0xffffff,
      map: texture,
    }); //材质对象Material
    var mesh1 = new THREE.Mesh(geometry1, material1); //
    // geometry1.faceVertexUvs
    mesh1.position.set(-1, 3, 2);
    mesh1.rotation.set(0.5 * Math.PI, 0, 0);

    // var div = document.createElement("div");
    // div.style.width = '200px';
    // div.style.height = '100px';
    // div.style.background = 'rgba(10,18,51,0.8)';
    // div.style.color = '#000'
    // div.textContent = 'hahaha'
    // div.className = 'label'
    // div.style.display = "block"
    // var ss=new Sensor('123',{x:1,y:1,z:1})
    // var moonLabel = new CSS2DObject(ss._div);
    // moonLabel.position.set(0, 0, 0);
    // moonLabel.visible=true;
    // mesh1.add(moonLabel);
    // scene.add(mesh1);
    // window.rs_div=ss

    // let sensor = new Sensor('123', 1, -1, 2, 1, '朝前');
    // let sensor2 = new Sensor('345', 2, -2, 3, 4, '朝前');
    // let sensor3 = new Sensor('678', 3, -6, 4, 4, '朝前');
    // scene.add(sensor._mesh);
    // scene.add(sensor2._mesh);
    // scene.add(sensor3._mesh);
    // var earthDiv = document.getElementById("label1");
    // var earthLabel = new CSS2DObject(earthDiv);
    // earthLabel.position.set(0, 1, 0);
    // mesh1.add(earthLabel);

    // model
    var onProgress = function (xhr) {
      if (xhr.lengthComputable) {
        var percentComplete = (xhr.loaded / xhr.total) * 100;
        var percent = document.getElementById('percent');
        percent.innerText = Math.round(percentComplete, 2) + '% 已经加载';
      }
    };
    var onError = function (xhr) {
      console.log(xhr);
    };

    var gltfLoader = new GLTFLoader();
    gltfLoader.setRequestHeader();
    gltfLoader.load(
      '/fsdownload/NewProject.gltf',
      (gltf) => {
        let obj = gltf.scene;
        obj.scale.set(0.0015, 0.0015, 0.0015);
        obj.rotation.set(-0.5 * Math.PI, 0, 0);

        //   gltf.scene.traverse( function ( child ) {
        //     if ( child.isMesh ) {
        //           child.material.emissive =  child.material.color;
        // child.material.emissiveMap = child.material.map ;
        //     }
        //   } );
        // scene.add(gltf.scenes)
        scene.add(gltf.scene);
      },
      onProgress,
      onError,
    );

    // var mtlLoader = new MTLLoader();
    // mtlLoader.load('/fsdownload/配电站模型1.mtl', function (materials) {
    //   materials.preload();

    //   var objLoader = new OBJLoader();
    //   objLoader.setMaterials(materials);
    //   objLoader.load('/fsdownload/配电站模型1.obj',
    //     function (object) {
    //       object.position.y = 0;
    //       object.rotation.y = 0;
    //       object.rotation.x = 0;
    //       object.emissive = 0x00ffff; //自发光颜色
    //       object.ambient = 0x00ffff; //环境光颜色
    //       object.scale.set(0.001, 0.001, 0.001);
    //       scene.add(object);
    //     },
    //     onProgress,
    //     onError,
    //   );
    // });
    // 渲染视图视角

    //   var fbx_loader = new FBXLoader()
    //   let url='/fsdownload/RAC_basic_sample_project-3DView.fbx'
    //   fbx_loader.load(url, function(object) {
    //     object.scale.multiplyScalar(0.1);    // 缩放模型大小
    //     scene.add(object);
    // }, onProgress, onError);

    camera.position.x = 20;
    camera.position.y = 20;
    camera.position.z = 20;
    camera.lookAt(scene.position);

    // fit camera to object
    // var bBox = new THREE.Box3().setFromObject(scene);
    // var height = bBox.size().y;
    // var dist = height / (2 * Math.tan(camera.fov * Math.PI / 360));
    // var pos = scene.position;

    // // fudge factor so the object doesn't take up the whole view
    // camera.position.set(pos.x, pos.y, dist * 1.5);
    // camera.lookAt(pos);
    // 浏览器窗口变动触发的方法
    // function onWindowResize() {
    //   // 重新设置相机宽高比例
    //   camera.aspect = window.width / window.height;
    //   // 更新相机投影矩阵
    //   camera.updateProjectionMatrix();
    //   // 重新设置渲染器渲染范围
    //   renderer.setSize( window.width,  window.height);
    //   labelRenderer.setSize(window.width, window.height)
    // }
    // window.addEventListener('resize', onWindowResize,false);
    renderScene();
    function renderScene() {
      var clock = new THREE.Clock();
      var delta = clock.getDelta();
      trackballControls.update(delta);
      requestAnimationFrame(renderScene);
      renderer.render(scene, camera);
      labelRenderer.render(scene, camera);
    }
  }, []);

  return (
    <div>
      <div>
        {messages.map((message) => (
          <h2>{message}</h2>
        ))}
      </div>
      <div id="inner-label" className="flex-between">
        <div>{/* {connectionStatus?'采集服务正常':'采集服务已断开'} */}</div>
        <div>
          <div id="percent"></div>
          {labelVisible ? (
            <EyeInvisibleOutlined
              style={{ float: 'right' }}
              onClick={() => {
                toggleSensorLabels();
              }}
            />
          ) : (
            <EyeOutlined
              style={{ float: 'right' }}
              onClick={() => {
                toggleSensorLabels();
              }}
            />
          )}
        </div>
      </div>
      <div id="canvas-frame"></div>
    </div>
    // <PageContainer>

    // </PageContainer>
  );
};

export default Detail;
